<script setup>
import {useWebSocket} from "@/utils/websocket.js";
import {useWebRtc} from "@/utils/webrtc.js";
import {Base64} from "js-base64";
import {ElMessage} from "element-plus";
const {webSocketInstance:ws} = useWebSocket(`ws://127.0.0.1:8199/websocket/server`,(code,data,message)=>{
  if (code === '200') {
    const {type, sdp, iceCandidate} = data
    if (type === "offer") {
      console.log('offer')
      answer(new RTCSessionDescription({ type, sdp }))
    } else if (type === "offer_ice") {
      console.log('offer_ice')
      peer.addIceCandidate(JSON.parse(iceCandidate))
    }
  }else if (code === '300') {
    ElMessage.error(data)
  }
})
const {peer} = useWebRtc()

const answer = async (sdp) => {
  await peer.setRemoteDescription(sdp)
  const answer = await peer.createAnswer()
  const data = {
    code: "200",
    message: "success",
    data: answer
  }
  ws.send(Base64.encode(JSON.stringify(data))); // 向服务端发送消息

  await peer.setLocalDescription(answer)
}


peer.ontrack = (e) => {
  console.log(e)
  if (e && e.streams) {
    console.log("收到对方音频/视频流数据...")
    let localVideo = document.getElementById("localVideo")
    localVideo.srcObject = e.streams[0]
    console.log(localVideo, e.streams)
  }
}
peer.onicecandidate = (e) => {
  console.log(e)
  if (e.candidate) {
    console.log("搜集并发送候选人")
    console.log(e.candidate)
    const data = {
      code: "200",
      message: "success",
      data: {type: `answer_ice`, iceCandidate: e.candidate}
    }
    ws.send(Base64.encode(JSON.stringify(data))); // 向服务端发送消息
  } else {
    console.log("候选人收集完成！")
  }
}


</script>

<template>
  <div class="server">
    <video id="localVideo" autoplay playsinline muted></video>
  </div>
</template>

<style scoped>
.server {

}

video {
  width: 80%;
  height: 80%;
  background: #000;
  position: absolute;
  left: 0;right: 0;
  top: 0;bottom: 0;
  margin: auto;
}


button {
  position: absolute;
  left: 0;right: 0;
  top: 0;bottom: 0;
  margin: auto;
  width: 130px;
  height: 40px;
  border-radius: 5px;
  padding: 10px 25px;
  font-weight: 500;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-block;
  border: none;
  color: #000;
  outline: none;
}
</style>